package com.zzyl.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.zzyl.base.PageBean;
import com.zzyl.constant.SuperConstant;
import com.zzyl.dto.RoleDto;
import com.zzyl.entity.Role;
import com.zzyl.entity.RoleResource;
import com.zzyl.mapper.RoleMapper;
import com.zzyl.mapper.RoleResourceMapper;
import com.zzyl.service.RoleService;
import com.zzyl.vo.RoleVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Arrays;
import java.util.List;

@Service
public class RoleServiceImpl implements RoleService {
    @Autowired
    private RoleMapper roleMapper;
    @Autowired
    private RoleResourceMapper resMapper;

    @Override
    public PageBean<RoleVo> page(Integer pageNum, Integer pageSize, RoleDto roleDto) {
        PageHelper.startPage(pageNum, pageSize);
        Page<Role> roles = roleMapper.selectPage(roleDto);
        return PageBean.of(roles, RoleVo.class);
    }

    @Override
    public void createRole(RoleDto roleDto) {
        Role role = BeanUtil.toBean(roleDto, Role.class);
        roleMapper.insert(role);
    }

    @Override
    public List<String> findCheckedResources(Long roleId) {

        return roleMapper.selectResourceNoByRoleId(roleId);
    }

    @Transactional
    @Override
    public void updateRole(RoleDto roleDto) {

        /*在多对多的关系时更新操作都是先删后加*/
        Role role = BeanUtil.toBean(roleDto, Role.class);

        roleMapper.updateByPrimaryKeySelective(role);

        //判断是否修改角色对应的资源数据
        if (ObjectUtil.isEmpty(roleDto.getCheckedResourceNos())) {
            return;
        }
        //删除原有角色资源中间信息
        resMapper.deleteByRoleId(role.getId());

        //保存角色资源中间信息
        Arrays.stream(roleDto.getCheckedResourceNos()).forEach(reNo -> {
            RoleResource resource = RoleResource.builder()
                    .roleId(role.getId())
                    .resourceNo(reNo)
                    .dataState(SuperConstant.DATA_STATE_0)
                    .build();
            resMapper.insert(resource);
        });
    }

    @Transactional
    @Override
    public void deleteRole(Long roleIds) {


        if (StrUtil.equals(SuperConstant.DATA_STATE_0, roleMapper.selectByPrimaryKey(roleIds).getDataState())) {

            throw new RuntimeException("该角色已被启动，无法删除");
        }
        roleMapper.deleteByPrimaryKey(roleIds);
        resMapper.deleteByRoleId(roleIds);
    }

    @Override
    public List<Role> list() {

        return roleMapper.list();
    }
}



